<template>
  <view class="vmall-order-list flex column">
    <view class="header pt-16">
      <!-- <view class="flex justify-between py-20">
        <up-search :placeholder="'输入商品名称、订单编号搜索'" v-model="keyword" :show-action="false" @clear="onClearSearch"
          clearabled />
        <view class="search-btn tc ml-16 f-28" @click="onSearch">搜索</view>
      </view> -->
      <!-- <up-tabs :list="tabList" :current="current" :lineColor="'rgba(214, 142, 68, 1)'" :lineWidth="'30'"
        :itemStyle="itemStyle" :activeStyle="activeStyle" :inactiveStyle="inactiveStyle" :keyName="name"
        @click="onTabChange" /> -->
        <tuitab :tabs="tabList" :current="current" :sliderBgColor="'rgba(214, 142, 68, 1)'" :selectedColor="'rgba(214, 142, 68, 1)'" scroll @change="onTabChange"></tuitab>
    </view>
    <view v-if="orderList.length > 0" class="container flex1">
      <swiper class="h100">
        <swiper-item>
          <scroll-view class="h100" scroll-y :enhanced="true" :show-scrollbar="false" @touchstart="touchStart"
            @touchend="touchEnd($event)" @scrolltolower="reachBottom">
            <view v-for="(item, index) in orderList" :key="index">
              <!-- <OrderCard :item="item" :buttonloading="buttonloading" @cancelpay="onCancelPay" @againorder="onAgainorder" @confirmapplyadjust="onConfirmApplyAdjust" @contrctkefu="contrctkefu" @onreceive="onReceiveOrder"    /> -->
               <view class="order-card mx-20 mt-24">
                <view class="item px-20 pt-16 pb-32 bg-white">
                  <view @click="onOrderDetail(item)">
                    <view class="flex justify-between my-20 f-24">
                      <view class="order-items">{{ item.shopName }}</view>
                      <view class="f-24" :class="item.status != 50 ? 'status-active' : 'status-text'">{{
                        statusText(item.status) }}
                      </view>
                    </view>
                    <view v-for="(nitem, index) in item.productList" :key="index">
                      <view class="order-itemscon">
                        <image class="cover mr-28" :src="nitem.image" />
                        <view class="py-24 flex justify-between items-center order-itemscon-right">
                          <view class="">
                            <view class="cart-title flex justify-start items-center">
                              <view class="tit">{{ nitem.name }}</view>
                            </view>
                            <view class="flex justify-between">
                              <text class="price1 f-32-B">￥{{ nitem.price }}</text>
                            </view>
                          </view>
                          <div class="order-count">
                            共{{ nitem.quantity }}件
                          </div>
                        </view>
                      </view>
                    </view>
                    <view class="shop flex justify-between items-center">
                      <view class="times">{{ item.createTime }}</view>
                      <view class="flex items-center price">
                        <text class="f-24">共{{ item.totalQuantity }}件商品</text>
                        <text class="f-24" v-if="role==2&&item.auditStatus==2">,实付金额:</text>
                        <text class="f-28 coloryellow1" v-if="role==2&&item.auditStatus==2">￥{{ item.orderAmount }}</text>
                      </view>
                    </view>
                  </view>
                  <view class="submit flex justify-end items-center mt-24">
                    <view class="btn tc f-24" v-if="item.status == 1 || item.status == 5" @click="contrctkefu">联系客服</view>
                    <view class="btn tc f-24" v-if="item.status == 1" @click="onCancelPay(item)">
                      <up-loading-icon class="loading" color="#fff" size="16"
                        :show="loading"></up-loading-icon><text>取消订单</text>
                    </view>
                    <view class="btn ml-20 tc f-24" v-if="item.status == 3 || item.status == 4 || item.status == 5"
                      @click="onOrderLogistics(item)">查看物流</view>
                    <view class="btn coloryellow ml-20 tc f-24" v-if="item.status == 4 || item.status == 5 || item.status == 6"
                      @click="onAgainorder(item)">
                      再下一单
                    </view>
                    <view class="btn ml-20 tc f-24" v-if="userInfo1Storge.isSupportChange&&item.status == 4 || item.status == 5&&item.showApplyAdjust"
                      @click="onConfirmApplyAdjust(item)">申请调货</view>
                    <view class="buy-btn ml-20 tc f-24" v-if="item.status == 3" @click="onReceiveOrder(item)">确认收货</view>
                  </view>
                </view>
               </view>
            </view>
          </scroll-view>
        </swiper-item>
      </swiper>
    </view>
    <!-- 暂无数据 -->
    <view v-else class="container flex1">
      <swiper class="h100">
        <swiper-item>
          <scroll-view class="h100" scroll-y :enhanced="true" :show-scrollbar="false" @touchstart="touchStart"
            @touchend="touchEnd($event)">
            <view class="empty-container flex justify-center items-center">
              <Empty :emptyInfo="emptyInfo" />
            </view>
          </scroll-view>
        </swiper-item>
      </swiper>
    </view>
  </view>
</template>

<script setup>
import { IMG_URL2 } from "@/config";
import OrderCard from "../components/order/card.vue";
import tuitab from "@/components/tui-tab.vue";
import Empty from "@/components/empty.vue";
import { shopApi } from "@/api";
import { getUserInfo } from "@/service";
import { getStorage } from "@/utils/storage";
let role=ref(getStorage('role'))
let userInfo1Storge = getUserInfo();
const EmptyImage = ref(IMG_URL2 + "empty/normal.png");

let buttonloading = ref(false)
const keyword = ref("");
const current = ref(0);
let loading=ref(false)
const itemStyle = ref({
  height: "40px"
});
const activeStyle = ref({
  fontWeight: "bold",
  fontSize: "14px",
  color: "#000000"
});
const inactiveStyle = ref({
  fontSize: "14px",
  color: "#000000"
});

const tabList = ref([
  {
    name: "全部",
    type: 0,
    isDot:false
  },
  {
    name: "待审核",
    type: 1,
    badge: {
      value: 0,
    },
    num:0,
    isDot:false
  },
  {
    name: "待发货",
    type: 2,
    badge: {
      value: 0,
    },
    num:0,
    isDot:false
  },
  {
    name: "待收货",
    type: 3,
    badge: {
      value: 0,
    },
    num:0,
    isDot:false
  },
  {
    name: "已完成",
    type: 4,
    isDot:false
  },
  {
    name: "退换货",
    type: 5,
    isDot:false
  }, {
    name: "已关闭",
    type: 6,
    isDot:false
  }
]);
const orderList = ref([]);
const pageParam = ref({
  status: "",
  page: 1,
  page_size: 10
});

// 订单状态
const statusText = (status) => {
  let text = "";
  switch (status) {
    case 1:
      text = "待审核";
      break;
    case 2:
      text = "待发货";
      break;
    case 3:
      text = "待收货";
      break;
    case 4:
      text = "已完成";
      break;
    case 5:
      text = "退换货";
      break;
    case 6:
      text = "已关闭";
      break;

    default:
      break;
  }
  return text;
};

const emptyInfo = ref({
  image: EmptyImage,
  width: 300,
  height: 300,
  tip: "暂无数据"
});
let orderStatus = ref(0)
let pageSize = ref(10)
let currentPage = ref(1)
let totalCount = ref(0)
const startX = ref();
onLoad((options) => {
  current.value = Number(options.type);
  orderStatus.value = Number(options.type);
  currentPage.value = 1
  getOrderList(1)
});

onShow(() => {
  getOrderCount()
  initList();
});

const getOrderCount = () => {
	shopApi.ORDERGETORDERCOUNT().then(res => {
		if(res.code==200){
			console.log(res.result)
			tabList.value[1].num = res.result.waitAudit //	待审核
      tabList.value[2].num = res.result.waitSend //待发货
			tabList.value[3].num = res.result.waitReceive	//待收货


		}
	})
}
// 初始化请求数据
const initList = () => {
  orderList.value = [];
  currentPage.value = 1
  getOrderList(1);
};

// 获取订单列表
const getOrderList = (type) => {
  let params = {
    currentPage: currentPage.value,
    pageSize: pageSize.value,
    productName:keyword.value
  }
  if (orderStatus.value != 0) {
    params.status = orderStatus.value
  }
  shopApi.ORDERGETORDERLIST(params).then((res) => {
    if (res.code == 200) {
      totalCount.value = res.result.totalCount;
      let list = res.result.data;
      if(type==1){
        orderList.value = list;
      }else{
        orderList.value = orderList.value.concat(list);
      }
    } else {
      uni.showToast({
        title: res.errMsg,
        icon: "success",
      });
    }
  })
};

// 搜索
const onSearch = () => {
  initList();
};
const onClearSearch = () => {
  keyword.value = "";
  initList();
};

// 触底加载
const reachBottom = () => {
  if (orderList.value.length >= totalCount.value) {
    loadStatus.value = "没有更多数据了";
    return
  }
  if (orderList.value.length < totalCount.value) {
    // pageParam.value.page++;
    currentPage.value++
    getOrderList(2);
  }
}
// onReachBottom(() => {
//   if (orderList.value.length >= totalCount.value) {
//     loadStatus.value = "没有更多数据了";
//     return
//   }
//   if (orderList.value.length < totalCount.value) {
//     pageParam.value.page++;
//     getOrderList(2);
//   }
// });

// 切换tab
const onTabChange = (e) => {
  current.value = e.index;
  orderStatus.value = e.type
  orderList.value = [];
  currentPage.value = 1
  getOrderList(1)
};

// 取消订单
const onCancelPay = (item) => {
  buttonloading.value = true;
  shopApi.ORDERCANCELORDER({
    id: item.orderId
  }).then((res) => {
    buttonloading.value = false;
    if (res.code == 200) {
      uni.showToast({
        title: "订单已取消",
        icon: "success",
        mask: true
      });
      initList()
      // for (let i = 0; i < orderList.value.length;) {
      //   if (orderList.value[i].orderId === item.orderId) {
      //     orderList.value.splice(i, 1);
      //   } else {
      //     i++;
      //   }
      // }
    } else {
      uni.showToast({
        title: res.errMsg,
        icon: "success",
      });
    }
  });
};


// 确认收货
const onReceiveOrder = (item) => {
  console.log(item,'item');
  buttonloading.value = true;
  shopApi.ORDERRECEIVEORDER({
    id: item.orderId
  }).then((res) => {
    buttonloading.value = false;
    if (res.code == 200) {
      uni.showToast({
        title: "确认成功",
        icon: "success",
        mask: true
      });
      initList()
    } else {
      uni.showToast({
        title: res.errMsg,
        icon: "success",
      });
    }
  });

};

// 联系客服
const contrctkefu=()=>{
  uni.navigateTo({ url: '/pages/user/customerservice' });
}

// 再下一单
const onAgainorder = (item) => {
  console.log(item,'item');
  buttonloading.value = true;
  shopApi.ORDERAGAINORDER({
    id: item.orderId
  }).then((res) => {
    buttonloading.value = false;
    if (res.code == 200) {
      uni.showToast({
        title: "再下一单成功",
        icon: "success",
        mask: true
      });
      initList()
    } else {
      uni.showToast({
        title: res.errMsg,
        icon: "success",
      });
    }
  });
}

// 申请调换货
const onConfirmApplyAdjust = (item) => {
  console.log(item,'item');
  uni.navigateTo({ url: "/pages/order/goodsexchange?id=" + item.orderId });
}

// 查看物流
const onOrderLogistics = (item) => {
  uni.navigateTo({ url: "/pages/order/logistics?id=" + item.orderId });
};

// 订单详情
const onOrderDetail = (item) => {
  uni.navigateTo({ url: "/pages/order/detail?id=" + item.orderId });
};

const touchStart = (e) => {
  startX.value = e.changedTouches[0].pageX; // 触摸目标在页面中的X坐标
  // console.log("开始触摸", startX.value);
};
const touchEnd = (e, index) => {
  // 手指离开屏幕时触发，获取滑动距离
  const moveX = e.changedTouches[0].pageX - startX.value;
  // 判断滑动方向
  if (moveX < -60) {
    if (current.value == 5) return;
    current.value++;
    orderStatus.value = tabList.value[current.value].type
    orderList.value = [];
    currentPage.value = 1
    getOrderList(1);
    // console.log("下一个");
  } else if (moveX > 60) {
    if (current.value == 0) return;
    current.value--;
    orderStatus.value = tabList.value[current.value].type
    orderList.value = []
    currentPage.value = 1
    getOrderList(1);
    // console.log("上一个");
  }
};
</script>

<style lang="scss">
page {
  background-color: #ededed;
}
</style>
<style lang="scss" scoped>
.vmall-order-list {
  height: 100vh;

  .header {
    position: fixed;
    width: 100%;
    box-sizing: border-box;
    background: #ffffff;
    z-index: 1000;

    .search-btn {
      width: 104rpx;
      height: 64rpx;
      line-height: 64rpx;
      background: rgba(214, 142, 68, 1);
      color: #ffffff;
      border-radius: 16rpx;
    }
  }

  .container {
    overflow: auto;
    // margin-top: 184rpx;
    margin-top: 84rpx;
    .item {
      border-bottom: 2rpx solid #eeeeee;

      .avatar {
        width: 96rpx;
        height: 96rpx;
      }
    }
  }

  .touch {
    height: 100vh;
  }

  .empty-container {
    margin-top: 68rpx;
    // background: #ffffff;
  }

  .divider {
    width: 440rpx;
    margin: 0 auto;
  }

  .order-card {
    .order-items {
      font-family: PingFang SC;
      font-size: 12px;
      font-weight: 400;
      line-height: 20px;
      text-align: left;
      text-underline-position: from-font;
      text-decoration-skip-ink: none;
      color: rgba(44, 44, 44, 1);
    }

    .status-text {
      color: #666666;
    }

    .status-active {
      color: rgba(214, 142, 68, 1);
    }

    .item {
      background: #ffffff;
      border-radius: 30rpx;

      .shop {
        width: 100%;
        margin-top: 12rpx;
        margin-bottom: 12rpx;

        .times {
          font-family: PingFang SC;
          font-size: 12px;
          font-weight: 400;
          line-height: 20px;
          color: rgba(0, 0, 0, 0.6);
        }

        .price {
          font-family: PingFang SC;
          font-size: 12px;
          font-weight: 400;
          line-height: 20px;
          color: rgba(0, 0, 0, 0.6);

          .coloryellow1 {
            color: rgba(214, 142, 68, 1);
          }
        }
      }

    }

    .img {
      margin-right: 12rpx;
      width: 40rpx;
      height: 40rpx;
      vertical-align: text-bottom;
    }

    .cover {
      width: 140rpx;
      height: 140rpx;
      border-radius: 16rpx;
    }

    .title {
      height: 74rpx;
    }

    .type {
      padding: 0rpx 20rpx;
      box-sizing: border-box;
      height: 56rpx;
      line-height: 56rpx;
      background: #6a1b99;
      color: #ffffff;
      border-radius: 16rpx 0rpx 16rpx 0rpx;
    }

    .submit {
      width: 100%;
      background: #ffffff;
      box-sizing: border-box;

      .other {
        color: #666666;
      }
    }

    .btn {
      width: 150rpx;
      height: 50rpx;
      line-height: 50rpx;
      background: #ffffff;
      color: rgba(0, 0, 0, 0.26);
      border-radius: 12rpx;
      border: 2rpx solid rgba(0, 0, 0, 0.26);
      margin-left: 12rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .coloryellow{
      background: rgba(214, 142, 68, 1) !important;
      color: #fff !important;
      border: 2rpx solid rgba(214, 142, 68, 1);
    }

    .buy-btn {
      width: 150rpx;
      height: 50rpx;
      line-height: 50rpx;
      background: #ffffff;
      color: rgba(214, 142, 68, 1);
      border-radius: 52rpx;
      border: 2rpx solid rgba(214, 142, 68, 1);
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .order-itemscon {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      margin-bottom: 12rpx;

      .order-itemscon-right {
        display: flex;
        align-items: center;
        width: calc(100% - 140rpx);

        .order-itemscon-right-price {
          color: rgba(214, 142, 68, 1);
          font-family: PingFang SC;
          font-size: 14px;
          font-weight: 400;
          line-height: 22px;
          text-align: left;
          text-underline-position: from-font;
          text-decoration-skip-ink: none;
        }

        .order-itemscon-right-count {
          color: rgba(0, 0, 0, 0.6);
        }
      }

      .cart-title {
        font-family: PingFang SC;
        font-size: 14px;
        font-weight: 400;
        line-height: 22px;
        text-align: left;
        text-underline-position: from-font;
        text-decoration-skip-ink: none;
        color: rgba(0, 0, 0, 1);

        .tit {
          font-family: PingFang SC;
          font-size: 14px;
          font-weight: 400;
          line-height: 22px;
          text-align: left;
          text-underline-position: from-font;
          text-decoration-skip-ink: none;
          color: rgba(0, 0, 0, 1);
        }
      }

      .price1 {
        color: rgba(0, 0, 0, 1);
        font-family: PingFang SC;
        font-size: 14px;
        font-weight: 400;
        line-height: 22px;
        text-align: left;
        text-underline-position: from-font;
        text-decoration-skip-ink: none;

      }

      .order-count {
        font-family: PingFang SC;
        font-size: 14px;
        font-weight: 400;
        line-height: 22px;
        text-align: left;
        text-underline-position: from-font;
        text-decoration-skip-ink: none;
        color: rgba(0, 0, 0, 0.6);
      }
    }
  }
}
</style>
